package com.config;

import com.pojo.Configuration;
import com.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * Created with IDEA by ChouFy on 2020/2/20.
 *
 * @author Zhoufy
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }


    public void parse(InputStream InputStream) throws DocumentException {
        Document document = new SAXReader().read(InputStream);
        Element rootElement = document.getRootElement();

        String namespaceURI = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        List<Element> insertElementList = rootElement.selectNodes("//insert");
        List<Element> deleteElementList = rootElement.selectNodes("//delete");
        List<Element> updateElementList = rootElement.selectNodes("//update");


        list.addAll(insertElementList);
        list.addAll(deleteElementList);
        list.addAll(updateElementList);


        for (Element element : list) {
            String labelName = element.getQName().getName();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sql);
            mappedStatement.setLabelName(labelName);
            System.out.println("namespaceURI:" + namespaceURI + "." + id);
            configuration.getMap().put(namespaceURI + "." + id, mappedStatement);
        }



    }
}
